package com.manage.cloud.customize;

import cn.hutool.json.JSONUtil;
import com.manage.cloud.utils.SecurityContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 授权失败自定义返回
 *
 * @author zhangqing
 */
@Component
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        log.error("访问 URL({}) 时，用户({}) 权限不够", request.getRequestURI(), Objects.requireNonNull(SecurityContextUtils.getLoginUser()).getUserId());
        try {
            response.getWriter().write(JSONUtil.toJsonPrettyStr("访问授权失败"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
